import router from '@/router'
import { useUserStore } from '@/stores'
import axios, { type Method } from 'axios'
import { showToast } from 'vant'

// 1. 创建一个axios实例对象
const baseURL = 'https://consult-api.itheima.net'
const instance = axios.create({
  baseURL,
  timeout: 10000
})

// 2. 配置请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 2.1 统一携带token
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers['Authorization'] = `Bearer ${store.user?.token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

//  3. 配置响应拦截器
instance.interceptors.response.use(
  (res) => {
    // 3.1 请求成功但业务失败
    if (res.data.code !== 10000) {
      showToast(res.data?.message || '业务处理失败')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (error) => {
    // 3.2 token失效
    // 1) 删除用户信息  2) 跳转到登录页(回到原来页面)
    if (error.response.status === 401) {
      const store = useUserStore()
      store.delUser()

      // 如何获取当前页面对应的路由地址
      // router.currentRoute.value.fullPath
      // fullPath 和 path 的区别
      // /home/cc 结果一致
      // /home/cc?a=1&b=2&c=3 => path:/home/cc  fullPath:/home/cc?a=1&b=2&c=3
      router.push({
        path: '/login',
        query: {
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(error)
  }
)

type Data<T> = {
  code: number
  message: string
  data: T
}

// 4. 封装请求工具函数
const request = <T>(
  url: string,
  method: Method = 'GET',
  submitObj?: Object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitObj
  })
}

export { baseURL, request }
